package com.x.Servlet_05_HttpServletApi;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;

/**
 * ClassName: HttpServletApiTest
 * Package: IntelliJ IDEA
 * Description:
 * Written by HanXu
 * Create 2024.08.07 17:00
 */
@WebServlet("/servlet2")
public class HttpServletRequestApi extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //方式一：获取所有参数名和参数值（参数值不一定唯一）
        Enumeration<String> parameterNames = req.getParameterNames();

        while (parameterNames.hasMoreElements()) {
            String pName = parameterNames.nextElement();
            //预防多值情况（参数不唯一）
            String[] parameterValues = req.getParameterValues(pName);

            if(parameterValues.length>1){
                System.out.println(pName+": "+Arrays.toString(parameterValues));
            }else
                System.out.println(pName+": "+parameterValues[0]);
        }

        System.out.println("+-----------------------------------------+");

        //方式二：获取所有参数名和参数值（参数值不一定唯一）
        Map<String, String[]> parameterMap = req.getParameterMap();
        Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet();

        for(Map.Entry<String, String[]> entry : entries){
            String[] values = entry.getValue();
            if(values.length>1){
                System.out.println(entry.getKey()+": "+Arrays.toString(values));
            }else
                System.out.println(entry.getKey()+": "+values[0]);

        }
    }
}
